package top.mall.happy.getway.filter;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;
import top.mall.happy.constant.auth.AuthConstant;
import top.mall.happy.getway.config.WhiteUrlConfig;

import java.net.URI;
import java.util.List;

@Component
public class WhiteUrlFilter implements WebFilter {

    @Autowired
    private WhiteUrlConfig whiteUrlConfig;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        URI uri = request.getURI();
        AntPathMatcher antPathMatcher = new AntPathMatcher();

        List<String> whiteUrls = whiteUrlConfig.getWhiteUrls();

        for (String url : whiteUrls) {
            if (antPathMatcher.match(url,uri.getPath())){
                request = exchange.getRequest().mutate().header(AuthConstant.JWT_TOKEN_HEADER, "").build();
                exchange = exchange.mutate().request(request).build();
                return chain.filter(exchange);
            }
        }
        return chain.filter(exchange);
    }

}
